<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { listSchedule } from '../../api/schedule'
import { listUsertable } from '../../api/usertable'
import { listDepartment } from '../../api/department'
import SearchForm from '../../components/SearchForm.vue'

// 定义班次类型选项
const shiftTypeOptions = [
  { value: 0, label: '早班' },
  { value: 1, label: '晚班' },
  { value: 2, label: '夜班' }
]

// 表格数据
const scheduleList = ref([])
const userList = ref([])
const departmentList = ref([])
const loading = ref(false)

// 查询参数
const queryParams = reactive({
  departmentId: undefined,
  dateRange: [],
  startDate: undefined,
  endDate: undefined
})

// 搜索表单配置
const searchConfig = ref([])

// 初始化搜索配置
const initSearchConfig = () => {
  searchConfig.value = [
    {
      type: 'select',
      label: '科室',
      field: 'departmentId',
      options: departmentList.value.map(item => ({
        label: item.departmentName,
        value: item.id
      }))
    },
    {
      type: 'date',
      label: '日期范围',
      field: 'dateRange',
      dateType: 'daterange',
      startPlaceholder: '开始日期',
      endPlaceholder: '结束日期',
      valueFormat: 'YYYY-MM-DD',
      rangeSeparator: '至'
    }
  ]
}

// 获取数据列表
const getList = async () => {
  loading.value = true
  try {
    const res = await listSchedule()
    scheduleList.value = res
  } catch (error) {
    console.error('获取排班列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取用户列表
const getUserList = async () => {
  try {
    const res = await listUsertable()
    userList.value = res.filter(item => item.roleId === 3) // 只筛选医护人员
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

// 获取科室列表
const getDepartmentList = async () => {
  try {
    const res = await listDepartment()
    departmentList.value = res
    // 更新搜索配置
    initSearchConfig()
  } catch (error) {
    console.error('获取科室列表失败:', error)
  }
}

// 搜索处理
const handleSearch = () => {
  getList()
}

// 重置处理
const handleReset = () => {
  Object.keys(queryParams).forEach(key => {
    queryParams[key] = undefined
  })
  getList()
}

// 表单项变化处理
const handleFormItemChange = ({ field, value }) => {
  if (field === 'dateRange' && value) {
    queryParams.startDate = value[0]
    queryParams.endDate = value[1]
  } else if (field === 'dateRange' && !value) {
    queryParams.startDate = undefined
    queryParams.endDate = undefined
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 获取用户名称
const getUserName = (userId) => {
  const user = userList.value.find(item => item.id === userId)
  return user ? user.userName : ''
}

// 获取科室名称
const getDepartmentName = (userId) => {
  const user = userList.value.find(item => item.id === userId)
  if (!user) return ''
  
  const department = departmentList.value.find(item => item.id === user.departmentId)
  return department ? department.departmentName : ''
}

// 根据科室ID筛选用户
const filteredUsers = computed(() => {
  if (!queryParams.departmentId) {
    return userList.value
  }
  return userList.value.filter(user => user.departmentId === queryParams.departmentId)
})

// 根据条件筛选排班数据
const filteredSchedules = computed(() => {
  let result = [...scheduleList.value]
  
  // 按科室筛选
  if (queryParams.departmentId) {
    const userIds = filteredUsers.value.map(user => user.id)
    result = result.filter(schedule => userIds.includes(schedule.userId))
  }
  
  // 按日期范围筛选
  if (queryParams.startDate && queryParams.endDate) {
    const startDate = new Date(queryParams.startDate)
    const endDate = new Date(queryParams.endDate)
    
    result = result.filter(schedule => {
      const scheduleDate = new Date(schedule.shiftDate)
      return scheduleDate >= startDate && scheduleDate <= endDate
    })
  }
  
  return result
})

// 导出排班表
const exportSchedule = () => {
  if (filteredSchedules.value.length === 0) {
    ElMessage.warning('没有可导出的数据')
    return
  }
  
  // 创建表格内容
  let content = '科室,医护人员,排班日期,班次类型\n'
  
  filteredSchedules.value.forEach(item => {
    const departmentName = getDepartmentName(item.userId)
    const userName = getUserName(item.userId)
    const date = formatDate(item.shiftDate)
    const shiftType = shiftTypeOptions.find(opt => opt.value === item.shiftType)?.label || ''
    
    content += `${departmentName},${userName},${date},${shiftType}\n`
  })
  
  // 创建并下载文件
  const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  
  link.setAttribute('href', url)
  link.setAttribute('download', `排班表_${new Date().toISOString().split('T')[0]}.csv`)
  link.style.visibility = 'hidden'
  
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  
  ElMessage.success('导出成功')
}

// 打印排班表
const printSchedule = () => {
  if (filteredSchedules.value.length === 0) {
    ElMessage.warning('没有可打印的数据')
    return
  }
  
  const printWindow = window.open('', '_blank')
  
  let printContent = `
    <!DOCTYPE html>
    <html>
    <head>
      <title>排班表</title>
      <style>
        body { font-family: Arial, sans-serif; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: center; }
        th { background-color: #f2f2f2; }
        h1 { text-align: center; }
        .print-header { text-align: center; margin-bottom: 20px; }
        @media print {
          .no-print { display: none; }
          button { display: none; }
        }
      </style>
    </head>
    <body>
      <div class="print-header">
        <h1>医院科室排班表</h1>
        <p>打印日期: ${new Date().toLocaleDateString()}</p>
      </div>
      <button class="no-print" onclick="window.print()">打印</button>
      <button class="no-print" onclick="window.close()">关闭</button>
      <table>
        <thead>
          <tr>
            <th>序号</th>
            <th>科室</th>
            <th>医护人员</th>
            <th>排班日期</th>
            <th>班次类型</th>
          </tr>
        </thead>
        <tbody>
  `
  
  filteredSchedules.value.forEach((item, index) => {
    const departmentName = getDepartmentName(item.userId)
    const userName = getUserName(item.userId)
    const date = formatDate(item.shiftDate)
    const shiftType = shiftTypeOptions.find(opt => opt.value === item.shiftType)?.label || ''
    
    printContent += `
      <tr>
        <td>${index + 1}</td>
        <td>${departmentName}</td>
        <td>${userName}</td>
        <td>${date}</td>
        <td>${shiftType}</td>
      </tr>
    `
  })
  
  printContent += `
        </tbody>
      </table>
    </body>
    </html>
  `
  
  printWindow.document.open()
  printWindow.document.write(printContent)
  printWindow.document.close()
  
  ElMessage.success('准备打印')
}

// 页面加载时获取数据
onMounted(() => {
  getUserList()
  getDepartmentList()
  getList()
})
</script>

<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="header-title">排班发布</span>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <SearchForm
        :config="searchConfig"
        v-model:queryParams="queryParams"
        @search="handleSearch"
        @reset="handleReset"
        @change="handleFormItemChange"
      >
        <template #buttons>
          <el-button type="primary" icon="Printer" @click="printSchedule">打印排班表</el-button>
          <el-button type="success" icon="Download" @click="exportSchedule">导出排班表</el-button>
        </template>
      </SearchForm>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="filteredSchedules"
        border
        style="width: 100%"
      >
        <el-table-column type="index" width="50" align="center" label="序号" />
        <el-table-column prop="userId" label="科室" align="center" :formatter="(row) => getDepartmentName(row.userId)" />
        <el-table-column prop="userId" label="医护人员" align="center" :formatter="(row) => getUserName(row.userId)" />
        <el-table-column prop="shiftDate" label="排班日期" align="center" :formatter="(row) => formatDate(row.shiftDate)" />
        <el-table-column prop="shiftType" label="班次类型" align="center" :formatter="(row) => shiftTypeOptions.find(opt => opt.value === row.shiftType)?.label || ''" />
      </el-table>
    </el-card>
  </div>
</template>

<style scoped>
.app-container {
  padding: 20px;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
}

.mb-4 {
  margin-bottom: 16px;
}
</style>